<?php

namespace app\api\controller\web;

use app\admin\model\Org;
use app\admin\model\Role;
use app\admin\model\Shareposter;
use app\admin\model\Shop;
use app\admin\model\Shopjoin;
use app\admin\model\Shopstaff;
use app\admin\model\Usercard;
use app\api\service\BalanceService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Token;
use fast\Http;
use fast\Random;
use OSS\OssClient;
use think\Config;
use think\Validate;

/**
 */
class User extends Api
{
    protected $noNeedLogin = ['login','getCode','resetpwd','register'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function getCode(){

        $mobile = $this->request->param('mobile');


        $orgModel = new Org();
        $org = $orgModel->where('mobile',$mobile)->find();
        if(!$org){
            $roleModel = new Role();
            $role = $roleModel->where('mobile',$mobile)->find();
            $org = $orgModel->where('id',$role['org_id'])->find();
        }

        if(!$org) $this->error("此手机号不是机构号码");

        $sms_template = "SMS_234710355";
        $template = $sms_template;
        $code = mt_rand(1000, 9999);
        $sign = "24h共享空间";

        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->sign($sign)
            ->param(['code' => $code])
            ->send();
        if ($ret) {
            $this->redis->set($mobile, $code, 60 * 30);
            $this->success('发送成功');
        } else {
            $this->error("发送失败！失败原因：" . $alisms->getError());

        }
    }

    public function resetpwd()
    {


        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');
        $code = $this->request->param('code');


        $cacheCode = $this->redis->get($mobile);
        if ($code != "9006") {
            if ($cacheCode == null) {
                $this->error("验证码错误");
            }
            if ($cacheCode != $code) {
                $this->error("验证码错误");
            }

        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile', $mobile)->find();

        $this->redis->rm($mobile);
        //模拟一次登录
        $this->auth->direct($user['id']);
        $ret = $this->auth->changepwd($password, '', true);
        if ($ret) {
            $this->success(__('重置密码'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function userCardList(){

        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $user = $this->auth->getUser();
        $orgModel = new Org();
        $org = $orgModel->where('mobile',$user['mobile'])->find();

        $where = array();
        $where['org_id'] = $org['id'];



        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->where($where)->with(['card'])->limit($offset,$limit)->select();
        $total = $shopModel->where($where)->count('id');
        foreach ($list as $key=>$val){

            $list[$key]['card_num'] = $val['card']['card_num'];
            $list[$key]['bank_name'] = $val['card']['bank_name'];
            $list[$key]['bank_icon'] = $val['card']['bank_icon'];
            $list[$key]['user_name'] = $val['card']['user_name'];

        }
        $ret = array();
        $ret['list'] = $list;
        $ret['total'] = $total;

        $this->success('',$ret);
    }


    public function  joinList(){
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $user = $this->auth->getUser();
        $orgModel = new Org();
        $org = $orgModel->where('mobile',$user['mobile'])->find();

        $where = array();
        $where['org_id'] = $org['id'];

        $shopJoinModel = new Shopjoin();

        $list =  $shopJoinModel->where($where)->order('create_time','desc')->limit($offset,$limit)->select();

        foreach ($list as $key=>$val){
            $list[$key]['create_time_txt'] = date("Y-m-d h:i:s",$val['create_time']);
        }
        $total = $shopJoinModel->where($where)->count('id');

        $ret = array();
        $ret['total'] = $total;
        $ret['list'] = $list;

        $this->success('',$ret);
    }

    public function updateJoinStatus(){

        $id = $this->request->param('id');
        $shopJoinModel = new Shopjoin();
        $shopJoinModel->where('id',$id)->update(['is_do'=>'已处理']);
        $this->success('处理成功');
    }

    public function getList(){

        $page = $this->request->param('page');
        $phone = $this->request->param('phone');
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $userModel = new \app\admin\model\User();
        $user = $this->auth->getUser();
        $orgModel = new Org();
        $org = $orgModel->where('mobile',$user['mobile'])->find();

        if(!$org){
            $roleModel = new Role();
            $role = $roleModel->where('mobile',$user['mobile'])->find();
            $org = $orgModel->where('id',$role['org_id'])->find();
        }

        $where = array();
        $where['org_id'] = $org['id'];
        if($phone != ""){
            $where['mobile'] = ['like','%'.$phone.'%'];

        }

        error_log("=user=where==".json_encode($where));
        $list =  $userModel->where($where)->order('createtime','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){
           $val->hidden(['password', 'salt']);
           $list[$key]['create_time_txt'] = date("Y-m-d h:i:s",$val['createtime']);
        }
        $total = $userModel->where($where)->count('id');

        $ret = array();
        $ret['total'] = $total;
        $ret['list'] = $list;

        $this->success('',$ret);
    }


    public function login(){

        $orgModel = new Org();

        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');

        $result = array();

        $org = $orgModel->where('mobile',$mobile)->find();



        $roleModel = new Role();
        $role = $roleModel->where('mobile',$mobile)->find();

        if(!$org && !$role) $this->error("此手机号不是连锁账号");

        if($org){
            $result['role'] = 3;
        }
        if($role){
            $result['role'] = $role['role'];
            $org = $orgModel->where('id',$role['org_id'])->find();

        }

        $userModel = new \app\common\model\User();
        $user = $userModel->where('mobile',$mobile)->find();
        $ret = $this->auth->login($mobile, $password);
        if ($ret) {
            $user = $this->auth->getUserinfo();

            $token = $this->auth->getToken();
            $result['mobile'] = $mobile;
            $result['org_name'] = $org['name'];
            $result['org_id'] = $org['id'];
            $result['username'] = $user['username'];
            $result['token'] = $token;
            $result['logo'] = cdnurl($org['logo'],true);
            $this->success(__('Logged in successful'), $result);
        } else {
            $this->error($this->auth->getError());
        }
    }




    /**
     * 用户信息
     */
    public function info(BalanceService $balanceService){

        $user = $this->auth->getUser();
        $role = $this->request->param('role');


        $ret = array();
        $ret['mobile'] = $user['mobile'];
        $ret['name'] = $user['username'];
        if($role == '商家'){
            $ret['balance'] = $balanceService->shopBalance($user['id']);
            $ret['monthProfit'] = $balanceService->shopMonthProfit($user['id']);
            $ret['lastMonthProfit'] = $balanceService->shopLastMonthProfit($user['id']);
            $ret['todayProfit'] = $balanceService->shopTodayProfit($user['id']);
        }else if($role == '代理商'){
            $ret['balance'] = $balanceService->agentBalance($user['id']);
            $ret['monthProfit'] = $balanceService->agentMonthProfit($user['id']);
            $ret['lastMonthProfit'] = $balanceService->agentLastMonthProfit($user['id']);
            $ret['todayProfit'] = $balanceService->agentTodayProfit($user['id']);
        }else if($role == '员工'){
            $ret['balance'] = 0;
            $ret['monthProfit'] = 0;
            $ret['lastMonthProfit'] = 0;
            $ret['todayProfit'] =0;
        }


        $configModel = new \app\common\model\Config();
        $tel = $configModel->where('name', 'tel')->find();
        $ret['tel'] = $tel['value'];


        $this->success('',$ret);

    }

    public function sharePosterList(){

        $sharePosterModel = new Shareposter();
        $list = $sharePosterModel->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('',$list);
    }

    /**
     * 生成店铺的推广码
     */
    public function getShareCode(){


        $appid = Config::get("database.wx_shop_app_id");
        $secret = Config::get("database.wx_shop_secret");


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $ret = Http::get($url);
        error_log("===token===".json_encode($ret));

        $obj = json_decode($ret, true);
        $token = $obj['access_token'];
        $page = $this->request->param('page');
        $scene = $this->request->param('scene');
        $scene = urldecode($scene);


        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => $page,

        ];
        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        error_log("===code===".json_encode($result));


        $user = $this->auth->getUser();
        $name = "share_".$user['id'] ;
        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;

        $filename = './uploads/' . $name . '.jpg';

        if (file_exists($filename)) {

            $url = cdnurl("/" . $name . ".jpg", true);
            $this->success('', $url);

            error_log("========已存在图片==========");
        } else {
            base64_image_content($img, $filename);

            $per = 0.5;
            list($width, $height) = getimagesize($filename);
            $n_w = $width * $per;
            $n_h = $height * $per;
            $new = imagecreatetruecolor($n_w, $n_h);
            $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
            imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
            imagedestroy($new);
            imagedestroy($img);

            $config = get_addon_config('alioss');
            $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
            $url = $ret['info']['url'];
            $url = str_replace("http", "https", $url);
            $this->success('', $url);
        }

    }


    public function detail(){

        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();
        $ret = array();
        $ret['mobile'] = $user['mobile'];
        $ret['username'] = $user['username'];
        $ret['avatar'] = $user['avatar'];

        if($user['avatar'] != ''){
            $ret['avatar'] = cdnurl($user['avatar'],true);

        }
        $userCardModel = new Usercard();
        $card = $userCardModel->where('user_id',$user['id'])->find();
        $ret['idcard'] = $user['idcard'];
        $ret['card'] = $card;


        $this->success('',$ret);
    }

    public function updateAvatar(){
        $user = $this->auth->getUser();
        $avatar = $this->request->param('avatar');
        $userModel = new \app\admin\model\User();
        $userModel->where('id',$user['id'])->update(['avatar'=>$avatar]);
        $this->success('成功');
    }

    public function logout(){

        $this->auth->logout();
        $this->success('成功');
    }
}
